package com.example.message2;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class Messages extends ListActivity{

	// All static variables
	// XML node keys
	static final String URL = "http://softeng.cs.uwosh.edu/students/cs342g2/php/pullMessages.php";
	// XML node keys
	static final String KEY_ITEM = "message"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_NAME = "from";
	static final String KEY_TO = "to";
	static final String KEY_DESC = "text";
	static final String KEY_READ = "read";
	static final String EXTRA_MESSAGE="";
	static final String EXTRA_MESSAGE2=""; 
	String loginStatus="not";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_messages);
		
		SharedPreferences settings = getSharedPreferences("preferences",0);
		int user=settings.getInt("curUser", -1);
		String password= settings.getString("curPassword","");
		
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL,user,password); // getting XML
		Document doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value
			map.put(KEY_ID, parser.getValue(e, KEY_ID));
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
			map.put(KEY_TO, "Rs." + parser.getValue(e, KEY_TO));
			map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
			map.put(KEY_READ, parser.getValue(e, KEY_READ));
			// adding HashList to ArrayList
			menuItems.add(map);
		}

		// Adding menuItems to ListView
				//ListView myList =(ListView)findViewById(android.R.id.list);
		
		
				ListAdapter adapter = new SimpleAdapter(this, menuItems,
						R.layout.list_item,
						new String[] { KEY_NAME, KEY_DESC, KEY_TO }, new int[] {
								R.id.name, R.id.desciption});

				setListAdapter(adapter);
				ListView lv = getListView();

				lv.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// getting values from selected ListItem
						String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
						//String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
						String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
						
						// Starting new intent
						Intent in = new Intent(getApplicationContext(), ViewMessage.class);
						in.putExtra(KEY_NAME, name);
						//in.putExtra(KEY_TO, cost);
						in.putExtra(KEY_DESC, description);
						startActivity(in);

					}});
				// selecting single ListView item
				//ListView lv = getListView();
				//lv.setOnItemClickListener(new OnItemClickListener(){
			
		//}
		findViewById(R.id.button2).setOnClickListener(       		 
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent myIntent = new Intent(Messages.this, MainActivity.class); 
						startActivityForResult(myIntent, 0);
						//close();
						Messages.this.finish();
					}
				});	

		findViewById(R.id.button1).setOnClickListener(       		 
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent myIntent = new Intent(Messages.this, SendMessage.class); 
						startActivityForResult(myIntent, 0);
						//close();
						Messages.this.finish();
					}
				});	



	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.message, menu);
		return true;
	}

	public class UserRegisterTask extends AsyncTask<String, String, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if (networkInfo != null && networkInfo.isConnected()) {
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(2);
				n.add(new BasicNameValuePair("uid", params[0]));
				n.add(new BasicNameValuePair("password", params[1]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/php/pullMessages.php?uid=1&password=password");
				// httppost.setEntity(new UrlEncodedFormEntity(n));

				try {
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost,
							respondHandler);
					success = true;

				} catch (Exception e) {

				}
			}

			return success;
		}

	}

	
}
